package com.atguigu.juc1205.demo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author Joey
 * @Date 2021/9/22 17:00
 * @Description 题目：三个售票员 卖出30张票
 * 笔记：如何编写企业级   多线程代码
 * 固定编程风格 + 模板 是什么
 * 1、在高内聚 低耦合的前提下，线程   操作  资源类
 * 1.1、一言不合先创建一个资源类
 */
public class SaleTicketDemo01 {

    public static void main(String[] args) {

        Ticket ticket = new Ticket();

        new Thread(() -> {for (int i = 0; i < 400; i++)ticket.sale();},"A").start();
        new Thread(() -> {for (int i = 0; i < 400; i++)ticket.sale();},"B").start();
        new Thread(() -> {for (int i = 0; i < 400; i++)ticket.sale();},"C").start();

        /*new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 400; i++) {
                    ticket.sale();
                }
            }
        }, "A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "B").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.sale();
                }
            }
        }, "C").start();*/

    }

}

/**
 * 资源类 实例变量 + 实例方法
 */
@Slf4j
class Ticket {

    private int number = 30;
    private Lock lock = new ReentrantLock();

    public void sale() {

        lock.lock();
        try {
            if (number > 0) {
                log.info("{}\t卖出第：{}张票，还剩下{}张", Thread.currentThread().getName(), number--, number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
